package com.test.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.test.config.AliPayConfig;
import com.test.entity.AliPay;
import com.test.entity.Jg;
import com.test.entity.Shop;
import com.test.service.JgService;
import com.test.service.ShopService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("alipay")
public class AliPayController {

    @Resource
    AliPayConfig aliPayConfig;

    @Resource
    private JgService jgService;

    @Resource
    private ShopService shopService;

    private static final String GATEWAY_URL = "https://openapi.alipay.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";

    @GetMapping("/pay") // id=xxx&traceNo=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        //从数据库中根据商品ID获取相关价格、名称信息
        Jg jg = jgService.queryById(aliPay.getId());
        aliPay.setSubject(jg.getSubject());
        aliPay.setTotalAmount(Double.parseDouble(jg.getTotalamount()));

        Shop shop = new Shop();
        shop.setOutTradeNo(aliPay.getTraceNo());
        shop.setTradeStatus("WAIT_BUYER_PAY");//状态为创建订单，但是未支付也未取消
        shopService.insert(shop);//插入订单信息

        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl("http://localhost:8081");

        //设置订单超时时间，有效时间为15分钟
        ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        ZonedDateTime futureTime = now.plusMinutes(15);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = futureTime.format(formatter);

        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\","
                + "\"time_expire\":\"" + formattedTime + "\"}");
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("/query")//根据订单号查询订单状态
    public String query(@RequestBody AliPay aliPay) {
        try {
            // 创建一个支付宝客户端
            AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                    aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            // 设置请求参数
            request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\"}");
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            System.out.println(response.getBody());
            JSONObject jsonObject = JSON.parseObject(response.getBody());
            // 获取 alipay_trade_query_response 对象
            JSONObject responseObject = jsonObject.getJSONObject("alipay_trade_query_response");
            // 获取 trade_status 值
            String trade_status = responseObject.getString("trade_status");
            Shop shop =  new Shop();
            shop.setOutTradeNo(aliPay.getTraceNo());
            shop.setTradeStatus(trade_status);
            shopService.update(shop);//更新订单信息
            return trade_status;
        } catch (Exception e) {
            return "fail";//请求失败，需要再次请求
        }
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            // 支付宝验签
            if (AlipaySignature.rsaCheckV1(params, aliPayConfig.getAlipayPublicKey(), CHARSET, SIGN_TYPE)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
            }
        }
        return "success";
    }
}

